<template>
  <form-dialop
    :title="item.length > 0 ? $t('common.ChangeSelfInfo') + '：' + username  : $t('common.CreateSystemAdmin')"
    :visible="visible"
    width="30%"
    @handleClose="handleClose"
  >
    <template #content>
      <el-form ref="form" :model="formData" :rules="formRule" label-width="120px">
        <el-form-item v-if="item.length < 1" :label="$t('user.Username')" prop="username">
          <el-input v-model="formData.username" :placeholder="$t('user.nameRequired')" @keyup.enter.native="submit" clearable />
        </el-form-item>
        <!-- <el-form-item v-if="item.length < 1" :label="$t('user.RealName')" prop="real_name">
          <el-input v-model="formData.real_name" :placeholder="$t('user.realNameRequired')" @keyup.enter.native="submit" clearable />
        </el-form-item> -->
        <el-form-item v-if="item.length < 1" :label="$t('user.Password')" prop="password">
          <el-input ref="passwordInput" type="password" v-model="formData.password" @keyup.enter.native="submit" :placeholder="$t('user.passwordPlaceholder')" show-password >
            <el-button slot="append" icon="el-icon-refresh-right" @click="randomPasswordString"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item v-if="false" :label="$t('user.Telephone')" prop="telephone">
          <el-input v-model="formData.telephone" @keyup.enter.native="submit" :placeholder="$t('user.telphonePlaceholder')" clearable />
        </el-form-item>
        <el-form-item :label="$t('user.MobliePhone')" prop="mobile">
          <el-input v-model="formData.mobile" @keyup.enter.native="submit" :placeholder="$t('user.mobilePhonePlaceholder')" clearable />
        </el-form-item>
        <el-form-item :label="$t('user.Email')" prop="email">
          <el-input v-model="formData.email" @keyup.enter.native="submit" :placeholder="$t('user.emailPlaceholder')" clearable />
        </el-form-item>
        <el-form-item :label="$t('user.Rules')" prop="rules">
          <el-select v-model="formData.rules" @keyup.enter.native="submit" :placeholder="$t('user.rulesPlaceholder')">
            <el-option v-for="role in roleList" :label="role.roleName" :value="role.id" :key="role.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.description')" prop="description">
          <el-input type="textarea" @keyup.enter.native="submit" v-model="formData.description" maxlength="200" show-word-limit :rows="3" :placeholder="$t('user.descriptionPlaceholder')" clearable />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submit" :disabled="loading">{{ $t('common.confirm') }}</el-button>
    </template>
  </form-dialop>
</template>
<script lang="ts">
import Vue from 'vue';
import FormDialop from '../../../components/Dialog/formDialog.vue';
import { randomPasswordString } from '../../../utils';
export default Vue.extend({
  props: {
    submitMethod: {
      type: Function,
      default() {
        return () => Promise.resolve();
      }
    }
  },
  components: {
    FormDialop
  },
  computed: {
    formRule() {
      if ((this as any).item.length > 0) {
        return {
          telephone: [
            { validator: (rule: any, value: any, callback: any) => {
                let rul = /^(0\d{2,3})-?(\d{7,8})$/;
                if(!value) {
                  return callback();
                }
                if(!rul.test(value)) {
                  callback(new Error((this as any).$t("user.telephoneRule")))
                } else {
                  callback();
                }
              }, trigger: 'blur'},
          ],
          mobile: [
            { validator: (rule: any, value: any, callback: any) => {
                let rul = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
                if(!value) {
                  return callback();
                }
                if(!rul.test(value)) {
                  callback(new Error((this as any).$t("user.mobileRule")))
                } else {
                  callback();
                }
              }, trigger: 'blur'},
          ],
          email: [
            { validator: (rule: any, value: any, callback: any) => {
              if (value !== '' && !/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value)) {
                callback(new Error((this as any).$t("user.emailRule")));
              } else {
                callback();
              }
            }, trigger: 'blur' }
          ],
          rules: [
            { required: true, message: (this as any).$t('user.RuleMenuRequired'), trigger: 'change' }
          ],
          description: [
            { max: 200, message: (this as any).$t('policy.message.descriptionLength').toString(), trigger: 'blur' }
          ]
        }
      } else {
        return {
          username: [
            { required: true, message: (this as any).$t('user.nameRequired'), trigger: 'blur' },
            { max: 30, message: (this as any).$t('user.nameMax'), trigger: 'blur' },
            { validator: (rule: any, value: any, callback: any) => {
              (this as any).$tunnyApi.apiGetSystemManagerList({}).then((res: Array<any>) => {
                if (res.findIndex((item: any) => item.username === value) !== -1) {
                  return callback(new Error((this as any).$t('user.nameRepeated')));
                } else {
                  return callback();
                }
              });
            }, trigger: 'blur' }
          ],
          // real_name: [
          //   { required: true, message: (this as any).$t('user.realNameRequired'), trigger: 'blur' },
          //   { max: 20, message: (this as any).$t('user.realNameMax'), trigger: 'blur' },
          //   { validator: (rule: any, value: any, callback: any) => {
          //     if (!/[\u4e00-\u9fa5]/.test(value)) {
          //       callback(new Error((this as any).$t("user.RealNameMustZH")));
          //     } else {
          //       callback();
          //     }
          //   } }
          // ],
          password: [
            { required: true, message: (this as any).$t('user.passwordRule.empty'), trigger: 'change' },
            { max: 30, message: (this as any).$t("user.passwordRule.inputMaxPW"), trigger: 'blur' },
            { validator: (rule: any, value: any, callback: any) => {
              if (!/(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{8,30}/.test(value)) {
                callback(new Error((this as any).$t("user.passwordRule.lowComplexityPW")))
                }else if (/[' '|\u4e00-\u9fa5\s]/.test(value)) {
                callback(new Error((this as any).$t('common.noZh')));
              } else {
                callback();
              }
            }, trigger: 'blur' }
          ],
          telephone: [
            { validator: (rule: any, value: any, callback: any) => {
                let rul = /^(0\d{2,3})-?(\d{7,8})$/;
                if(!value) {
                  return callback();
                }
                if(!rul.test(value)) {
                  callback(new Error((this as any).$t("user.telephoneRule")))
                } else {
                  callback();
                }
              }, trigger: 'blur'},
          ],
          mobile: [
            { max: 11, message: (this as any).$t("user.telephoneMaxRule"), trigger: 'blur' },
            { validator: (rule: any, value: any, callback: any) => {
                let rul = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
                if(!value) {
                  return callback();
                }
                if(!rul.test(value)) {
                  callback(new Error((this as any).$t("user.mobileRule")))
                } else {
                  callback();
                }
              }, trigger: 'blur'},
          ],
          rules: [
            { required: true, message: (this as any).$t('user.RuleMenuRequired'), trigger: 'change' }
          ],
          email: [
            { validator: (rule: any, value: any, callback: any) => {
              if (value !== '' && !(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value))) {
                callback(new Error((this as any).$t("user.emailRule")));
              } else {
                callback();
              }
            }, trigger: 'blur' }
          ],
          description: [
            { max: 200, message: (this as any).$t('policy.message.descriptionLength').toString(), trigger: 'blur' }
          ]
        }
      }
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      item: [],
      formData: {
        // real_name: "",
        rules: "",
        password: "",
        telephone: "",
        mobile: "",
        email: "",
        description: ""
      },
      username: '',
      roleList: []
    }
  },
  methods: {
    init(item: any) {
      (this as any).item = [];
      (this as any).accountName = "";
      (this as any).formData = {
        // real_name: "",
        rules: "",
        password: "",
        telephone: "",
        mobile: "",
        email: "",
        description: ""
      };
      if (item != undefined) {
        (this as any).username = item[0].username;
      }
      (this as any).visible = true;
      if (item) {
        item.forEach((i: any) => (this as any).item.push(JSON.parse(JSON.stringify(i))));
        // (this as any).formData.real_name = (this as any).item[0].real_name;
        (this as any).formData.rules = (this as any).item[0].role_id;
        (this as any).formData.password = (this as any).item[0].password;
        (this as any).formData.telephone = (this as any).item[0].telephone;
        (this as any).formData.mobile = (this as any).item[0].mobile;
        (this as any).formData.email = (this as any).item[0].email;
        (this as any).formData.description = (this as any).item[0].description;
      } else {
        (this as any).item = [];
        (this as any).formData = {
          // real_name: "",
          rules: "",
          password: "",
          telephone: "",
          mobile: "",
          email: "",
          description: ""
        };
        (this as any).$nextTick(() => {
          (this as any).$refs['passwordInput'].passwordVisible = true;
        });
      }
      (this as any).getAllRules();
      (this as any).$nextTick(() => {
        (this as any).$refs.form.clearValidate();
      });
    },
    submit() {
      (this as any).$refs.form.validate((valid: any) => {
        if (valid) {
          (this as any).loading = true;
          if ((this as any).item.length > 0) {
            delete (this as any).formData.password;
          }
          (this as any).submitMethod((this as any).item, (this as any).formData).then(() => {
            (this as any).$message.success((this as any).item.length > 0 ? (this as any).$t('common.changeSuccess') : (this as any).$t('user.createSystemSuc'));
            (this as any).handleClose();
          }).catch(()=>{
            (this as any).$message.error((this as any).item.length > 0 ? (this as any).$t('common.changeError') : (this as any).$t('user.createSystemFail'));
            (this as any).handleClose();
          }).finally(() => {
            (this as any).loading = false;
          });
        }
      });
    },
    handleClose() {
      (this as any).visible = false;
      this.loading = false;
      (this as any).$nextTick(() => {
        (this as any).$refs.form.clearValidate();
      });
    },
    randomPasswordString() {
      const rp = randomPasswordString();
      (this as any).formData.password = rp;
    },
    getAllRules() {
      this.$systemTunnyApi.getAllRules().then((result: any) => {
        console.log("getAllRules", result);
        this.roleList = result.data;
      });
    }
  }
})
</script>

<style lang="scss" scoped>
.el-form-item {
  display: flex;

  .el-form-item__label {
    flex-shrink: 0;
  }

  .el-form-item__content {
    flex-grow: 1;
  }
}
</style>
